package lab3;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.PriorityQueue;
import java.util.Scanner;

public class Spanning {
	private static ArrayList<String> vertices;
	private static PriorityQueue<Edge> edges;
	private static PriorityQueue<Edge> temporaryEdges;
	private static ArrayList<String> newVertices;
	private static ArrayList<Edge> newEdges;
	private static int weight;

	public static void main(String[] args) {
		vertices = new ArrayList<String>();
		edges = new PriorityQueue<Edge>();
		temporaryEdges = new PriorityQueue<Edge>();
		newVertices = new ArrayList<String>();
		newEdges = new ArrayList<Edge>();
		try {
			FileInputStream is = new FileInputStream(args[0]);
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String[] city1;
			String[] city2;
			String[] distance;
			String line = "";
			while ((line = br.readLine()) != null && line.indexOf("--") == -1) {
				vertices.add(line);
				System.out.println(line);
			}

			city1 = line.split("--");
			city2 = city1[1].split(" \\[");
			distance = city2[1].split("\\]");
			System.out.println("City1 " + city1[0]);
			System.out.println("City2 " + city2[0]);
			System.out.println("Distance " + distance[0]);
			edges.add(new Edge(city1[0], city2[0], Integer
					.parseInt(distance[0])));

			while ((line = br.readLine()) != null) {
				city1 = line.split("--");
				city2 = city1[1].split(" \\[");
				distance = city2[1].split("\\]");
				System.out.println(distance[0]);
				edges.add(new Edge(city1[0], city2[0], Integer
						.parseInt(distance[0])));
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Edge edge;
		edge = edges.poll();
		newVertices.add(edge.vertice1);
		newVertices.add(edge.vertice2);
		weight += edge.length;
		System.out.println("\n" + edge.length);
		while (vertices.size() > newVertices.size()) {
			edge = edges.poll();
			System.out.println(edge.vertice1 + " " + edge.vertice2 + " "
					+ edge.length);
			if (newVertices.contains(edge.vertice1)
					&& !newVertices.contains(edge.vertice2)) {
				newVertices.add(edge.vertice2);
				weight += edge.length;
				addBackTemporaryEdges();
				System.out.println("Vertice2 " + edge.vertice2);
			} else if (!newVertices.contains(edge.vertice1)
					&& newVertices.contains(edge.vertice2)) {
				newVertices.add(edge.vertice1);
				weight += edge.length;
				addBackTemporaryEdges();
				System.out.println("Vertice1 " + edge.vertice1);
			} else {
				temporaryEdges.add(edge);
			}
			// System.out.println("Edge length: " + edge.length + " weight: " +
			// weight);
		}

		System.out.println(newVertices.size());
		System.out.println("Weight: " + weight);
	}
	
	private static void addBackTemporaryEdges() {
		Edge edge;
		while((edge = temporaryEdges.poll()) != null)
			edges.add(edge);
	}

}
